package jannex.internal;

import jannex.sql.JxBatchUpdateException;
import jannex.JannexException;
import jannex.sql.JxSqlException;
import jannex.sql.JxSqlFeatureNotSupportedException;
import jannex.sql.JxTransientException;

import java.sql.BatchUpdateException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLTransientException;

public final class ExceptionFactory {

    // SQLException
    //   BatchUpdateException (done)
    //   SQLWarning
    //     DataTruncation
    //   SQLClientInfoException (not duped)
    //   SQLNonTransientException
    //     SQLDataException (duped)
    //     SQLFeatureNotSupportedException (duped)
    //     SQLIntegrityConstraintViolationException (duped)
    //     SQLInvalidAuthorizationSpecException (duped)
    //     SQLNonTransientConnectionException
    //     SQLSyntaxErrorException
    //   SQLRecoverableException
    //   SQLTransientException (done)
    //     SQLTimeoutException
    //     SQLTransactionRollbackException
    //     SQLTransientConnectionException


    private ExceptionFactory() {}

    public static RuntimeException make(Exception e) {
        if (!(e instanceof SQLException)) {
            if (e instanceof RuntimeException) {
                return (RuntimeException) e;
            }
            return new JannexException(e);
        }

        SQLException sqlException = (SQLException) e;
        String sqlState = sqlException.getSQLState();
        String reason = sqlException.getMessage();
        int vendorCode = sqlException.getErrorCode();

        if (e instanceof SQLFeatureNotSupportedException) {
            throw new JxSqlFeatureNotSupportedException(e.getMessage(), e.getCause(), vendorCode, sqlState);
        } if (e instanceof SQLTransientException) {
                return new JxTransientException(reason, e, vendorCode, sqlState);
        } else if (e instanceof BatchUpdateException) {
            return new JxBatchUpdateException(reason, e, vendorCode, sqlState, ((BatchUpdateException) e).getUpdateCounts());
        }

        return new JxSqlException(reason, e, vendorCode, sqlState);
    }
}
